<?php
/* 
* @Author: LDF QQ 47121862
* @Date:   2014-05-27 13:42:14
* @Last Modified by:   LDF QQ 47121862
* @Last Modified time: 2014-06-09 08:47:36
*/
class IndexControl extends Control{
	public function index(){
		// p($_SESSION);
		// print_const();
		$category = cache('categoryCache');
		$category = Data::channelLevel($category);
		// p($category);
		$cate = M('category')->all();
		$jiadian = Category::getChildsAll($cate,7);

		// 3f服饰鞋包
		$f3 = M('category')->where('gtid=1 and pid<>0 and cate_type=2')->all();
		// 4f珠宝数码
		$f4 = M('category')->where('gtid=3 and pid<>0 and cate_type=2')->all();
		

		$this->assign('jiadian',$jiadian); //1f
		$this->assign('f3',$f3);
		$this->assign('f4',$f4);
		$this->news=M('news')->limit(12)->all(); //分配快报
		$this->assign('category',$category);
		$this->display('index.html');
	}
	//分配栏目到分类列表
	public function category(){
		$cid = Q('cid',0,'intval');
		$categoryCache=cache('categoryCache');
		//如果不是正常进入，返回首页
		if(!isset($categoryCache[$cid])) go(__ROOT__);
		//如果参数没有s变量生成此变量
		if(!Q('get.s')){ //生成 0-0-0-0-0-0
			$gtid=$categoryCache[$cid]['gtid'];
			$totalAttrClass=M('attr_class')->where('gtid='.$gtid)->count();
			$attrUrl='';
			for($i=0;$i<$totalAttrClass;$i++){
				$attrUrl.='-0';
			}
			$attrUrl=substr($attrUrl, 1);
			go(U('category',array('cid'=>$cid,'s'=>$attrUrl)));
		}
		//分配左侧栏目属性
		$category = M('category')->where('cid='.$cid)->find();
		$this->category=$category;
		$cates = M('category')->all();
		$this->cate = Category::getChildsAll($cates,$category['cid']);
		// $this->cate = M('category')->where('gtid='.$category['gtid'])->all();
		//分配商品列表
		$this->assignGoods($cid);
		//查找面包屑
		$tips = Category::getParents($categoryCache,$cid);
		// p($tips);
		//分配面包屑
		$this->tips=$tips;
		//分配搜索属性
		$this->assignSerachAttr($cid);
		$this->display('goodsList.html');
	}
	//分配商品
	public function assignGoods($cid){
		// print_const();
		$order = isset($_GET['order'])?'price ASC':'addtime DESC';
		$s=explode('-',Q('s'));
		//移除属性为0的值
		$arr=array();
		foreach ($s as $k => $v) {
			if($v==0) continue;
			$arr[]=$v;
		}
		if($arr){ //组合sql语句，查询属性值并分配
			$this->handleSql($arr,$cid);
		}else{
			$page=new page(M('goods')->where('cid='.$cid)->count(),20);
			$data = M('goods')->limit($page->limit())->where('cid='.$cid)->order($order)->all();
			$this->page=$page->show(2);
			$this->goods=$data;
		}
	}
	//分配搜索属性
	public function assignSerachAttr($cid){
		$categoryCache=cache('categoryCache'); //栏目
		$goodsTypeCache=cache('goodsType');		//商品类型
		$gtid=$categoryCache[$cid]['gtid'];
		$attrClass=M('attr_class')->where('gtid='.$gtid)->all(); //查询类型
		foreach ($attrClass as $k => $v) {	//组合
			$attrClass[$k]['attrValue']=M('attr_value')->where('acid='.$v['acid'])->all();
		}
		$this->attrClass=$attrClass;
	}
	/**
	 * [handleSql 组合查询属性sql并分配变量]
	 * SELECT * FROM hd_g_goods AS g JOIN
    * hd_g_goods_attr AS a0 JOIN hd_g_goods_attr AS a1 JOIN hd_g_goods_attr AS a2 
    * ON 
    * a0.gid= a1.gid AND a1.gid= a2.gid
    * AND g.gid= a0.gid
    * WHERE a0.avid=1 AND a1.avid=2 AND a2.avid=6
    * AND g.cid=7
	 * @param  [type]  $arr [description]
	 * @param  integer $cid [description]
	 * @return [type]       [description]
	 */
	private function handleSql($arr,$cid=0){
		$table=C('DB_PREFIX').'goods_attr';
		$JOIN='';$ON=' ON ';$WHERE=' WHERE ';
		foreach ($arr as $k => $v) {
			$JOIN.=' JOIN '.$table.' AS a'.$k;
			$WHERE.='a'.$k.'.avid='.$v.' AND ';
		}
		for($i=0;$i<count($arr)-1;$i++){
			$ON.='a'.$i.'.gid=a'.($i+1).'.gid AND ';
		}
		$ON.='g.gid=a0.gid';
		$WHERE.='g.cid='.$cid;
		//获取所有数据用于分页
		$count=M()->query("SELECT count(*) AS c FROM hd_g_goods AS g ".$JOIN.$ON.$WHERE);
		$page=new page($count[0]['c'],20);
		$sql = "SELECT * FROM hd_g_goods AS g ".$JOIN.$ON.$WHERE.' LIMIT '.$page->limit(1);
		$data=M()->query($sql);

		$this->page=$page->show(2);
		$this->goods=$data;
	}















	//商品内容展示页
	public function content(){
		$gid=Q('gid');
		$categoryCache=cache('categoryCache');
		$goodsTypeCache=cache('goodsTypeCache');
		$goods=M('goods')->find($gid);
		$gtid=$categoryCache[$goods['cid']]['gtid'];
		$pre = C('DB_PREFIX');
		//分配商品规格
		$attrClass=M('attr_class')->where('is_spec=1')->all("gtid=$gtid");
		foreach ($attrClass as $k => $v) {
			$sql="SELECT ga.avalue,ga.avid FROM {$pre}attr_value AS av 
					JOIN {$pre}goods_attr AS ga ON av.avid=ga.avid 
					WHERE ga.gid={$gid} AND av.acid={$v['acid']}
					";
			$attrClass[$k]['_val']=M()->query($sql);
		}
		// p($attrClass);
		//判断是否第一次加载
		$avid=Q('avid');
		if($avid){ //此时avid格式为   3_12格式
			$stid=$this->getStock($gid,$avid);
			if($stid){
				$stock=M('stock')->where("gid=$gid")->find($stid);
				$stVal=explode('_', $avid);
			}else{
				$stVal=explode('_', $avid);
			}
		}else{ //第一次加载，就分配avid.取库存表第一条数据，让其商品规格默认选中一个属性
			$stock=M('stock')->find("gid=$gid");
			//获取当前商品第一条库存属性值id
			$stVal=M('stock_attr')->where("stid={$stock['stid']}")->getField('avid',1);
		}
		//查询商品图片
		$pic=M('goods_pic')->where("gid=$gid")->all();
		//查找面包屑
		$tips = Category::getParents($categoryCache,$goods['cid']);
		// p($tips);
		//分配面包屑
		$this->tips=$tips;
		//分配产品图片
		$this->pic=$pic;
		//分配产品
		$this->field=array_merge($goods,$stock);
		//分配属性
		$this->attrClass=$attrClass;
		//分配属性默认选中
		$this->stVal=$stVal;

		// p($goods);

		$this->display('goodsContent.html');
	}

	//Ajax查询库存
	public function havingst(){
		$gid=Q('gid');
		$avid=Q('avid');
		$s = $this->getStock($gid,$avid);
		if($s){
			echo 1;exit;
		}else{
			echo 0;exit;
		}
	}

	/**
	 * 根据gid,avid属性获得库存ID
	 * @param  [type] $gid  [description]
	 * @param  [type] $avid [3_12或者array()]
	 * @return [type]       [description]
	 */
	public function getStock($gid,$avid=array()){
		$pre=C('DB_PREFIX');
		if(strstr($avid, '_')){
			$avid=explode('_', $avid);
		}else{
			if(!is_array($avid)) return false;
		}
		//组合SQL语句
		// select * from hd_g_stock_attr as a0 join hd_g_stock_attr as a1
		// ON a0.stid = a1.stid
		// WHERE a0.avid=6 AND a1.avid=13
		// AND a0.gid=1
		$JOIN='';$ON=' ON ';$WHERE=' WHERE ';
		foreach ($avid as $k => $v) {
			$JOIN.=' JOIN '.$pre.'stock_attr AS a'.$k;
			$WHERE.='a'.$k.'.avid='.$v.' AND ';
		}
		$JOIN=substr($JOIN,5);
		for($i=0;$i<count($avid)-1;$i++){
			$ON.='a'.$i.'.stid=a'.($i+1).'.stid AND ';
		}
		$ON=substr($ON,0,-4);
		$WHERE.='a0.gid='.$gid;
		$SQL="SELECT a0.stid FROM ".$JOIN.$ON.$WHERE;
		// 根据avid自关联stock_attr表查询是否有商品
		$re = M()->query($SQL);
		//返回库存id
		return $re?$re[0]['stid']:null;
	}






















	//重构display方法
	public function display($tplFile = null, $cacheTime = null, $cachePath = null, $stat = false, $contentType = "text/html", $charset = "", $show = true)
	{
		$tplFile = C('TPL_PATH').C('TPL_STYLE').'/'.$tplFile;
		parent::display($tplFile);
	}
}
